var MD5Encode = require("MD5Encode.js");

const formatTime = date => {
  var date = new Date()
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

function timestamp() {
  return new Date().getTime()
}

function sign(data, appkey) {
  console.log(data);
  appkey = "wTB4+q'DoE2Px}t#" + appkey;
  var newdata = objKeySort(data);
  console.log(newdata+appkey)
  var sign = md5(newdata + appkey);
  return sign
}

function objKeySort(obj) {//排序的函数
  var newkey = Object.keys(obj).sort();
  var str = '';
  str += '&' ;
  //先用Object内置类的keys方法获取要排序对象的属性名，再利用Array原型上的sort方法对获取的属性名进行排序，newkey是一个数组

  for (var i = 0; i < newkey.length; i++) {//遍历newkey数组
    str +=  newkey[i] + obj[newkey[i]];
  }
  return str.substring(1);//返回排好序的新对象
}

function doMD5Encode(toEncode) {
  return MD5Encode.hexMD5(toEncode);
}

function md5(str) {
  return doMD5Encode(str).toUpperCase();
}

module.exports = {
  formatTime: formatTime,
  timestamp: timestamp,
  sign: sign
}
